<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    .none {
      -webkit-filter: none;
    }

    .blur {
      -webkit-filter: blur(3px);
    }

    .grayscale {
      -webkit-filter: grayscale(1);
    }

    .invert {
      -webkit-filter: invert(1);
    }

    .sepia {
      -webkit-filter: sepia(1);
    }
  </style>
</head>
<body>
<div>
  <label>audio source:</label>
  <select id="audioSource"></select>
  <label>audio output:</label>
  <select id="audioOutput"></select>
  <label>video source:</label>
  <select id="videoSource"></select>
  <label>filter:</label>
  <select id="filter">
    <option value="none">None</option>
    <option value="blur">Blur</option>
    <option value="grayscale">Grayscale</option>
    <option value="invert">Invert</option>
    <option value="sepia">Sepia</option>
  </select>
  <video autoplay playsinline id="player"></video>
</div>
<script src="../static/adapter.js"></script>
<script src="../utils/utils.js"></script>
<script>
  'use strict'

  var $videoPlay = $('video#player')
  var $audioSource = $('#audioSource')
  var $audioOutput = $('#audioOutput')
  var $videoSource = $('#videoSource')
  var $filter = $('#filter')

  /**
   * 获取到流， 直接赋值给 video
   *
   * @param stream
   * @returns {Promise<MediaDeviceInfo[]>}
   */
  function gotMediaStream (stream) {
    $videoPlay.srcObject = stream

    // 返回设备信息列表
    return navigator.mediaDevices.enumerateDevices()
  }

  /**
   * 设备信息
   * @param deviceInfos
   */
  function gotDevices (deviceInfos) {
    var option = document.createElement('option')

    option.text = deviceInfos.label;
    option.value = deviceInfos.deviceId;

    if (deviceInfos.kind === 'audioinput') {
      $audioSource.appendChild(option)
    } else if (deviceInfos.kind === 'audiooutput') {
      $audioOutput.appendChild(option)
    } else if (deviceInfos.kind === 'videoinput') {
      $videoSource.appendChild(option)
    }
  }

  /**
   * 获取设备信息以及权限
   * 切换浏览器或者重新打开，都需要重新调用 || 重新获取。
   */
  function start () {
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      console.log('getUserMedia is not supported!')
    } else {
      var deviceId = $videoSource.value
      var constraints = {
        video: {
          width: 320,
          height: 240,
        },
        audio: {
          // 降噪 开启
          noiseSuppression: true,
          // 回音消除 开启
          echoCancellation: true,
          // 没有值，会使用默认的，有值则使用选中的。
          deviceId: deviceId ? deviceId : undefined
        },
      }
      navigator.mediaDevices.getUserMedia(constraints)
        .then(gotMediaStream)
        .then(gotDevices)
        .catch(handleError)
    }
  }

  start ()

  $videoSource.onchange = start;

  $filter.onchange = function () {
    $videoPlay.className = $filter.value
  }
</script>
</body>
</html>
